/*
 * @Author: sunzhongjie
 * @Date: 2020-12-03 11:34:43
 * @LastEditors: Jelly
 * @LastEditTime: 2020-12-17 19:24:42
 */
var redis = require('redis'),
    redis_data = require('./redis_data_test.js'),
    env = require('./config.js'),
    { REDIS_HOST, REDIS_PORT, REDIS_OPTS = {}, REDIS_AUTH, REDIS_DB } = env.dev;
    // { REDIS_HOST, REDIS_PORT, REDIS_OPTS = {}, REDIS_AUTH } = env.pro;
console.log(REDIS_HOST, REDIS_PORT, REDIS_OPTS);
let client = redis.createClient(REDIS_PORT, REDIS_HOST, REDIS_OPTS);
// client.auth(REDIS_AUTH, function() {
//   console.log("auth success");
// });
client.on('connect', async function () {
  console.log("Redis connect success!");
  let meta = await hgetall(REDIS_DB);
  if(!meta) {
    Object.keys(redis_data).forEach(e => {
      // console.log(e)
      client.hmset(REDIS_DB, e.toLowerCase(), JSON.stringify(redis_data[e]))
    })
  }
});
client.on('ready', function() {
  console.log('开始使用: Ready')
});

/*
@param{name}: redis中的对应数据库名
@param{key}: redis中的name数据库中所需要数据的字段名key
@param{res}: redis中的name数据库中所需字段名key对应的数据
*/
const hget = (name, key) => {
  return new Promise((resolve, reject) => {
    client.hget(name, key, (err, res) => {
      if(err) {
        reject(err);
      } else {
        // typeof res === 'string
        resolve(JSON.parse(res))
      }
    });
  })
}
/*
@param{name}: redis中的数据库名
@param{res}: redis中的name数据库中所有的数据
*/
const hgetall = (name) => {
  return new Promise((resolve, reject) => {
    client.hgetall(name, (err, res) => {
      if(err) {
        reject(err);
      } else {
        // typeof res === 'object
        resolve(res);
      }
    });
  })
}
const hset = (name, key, data) => {
  return new Promise((resolve, reject) => {
    if (key) {
      client.set(name, key, JSON.stringify(data), (err, reply) => {
        if (err) {
          reject(err);
        } else {
          resolve(reply);
        }
      });
    } else {
      client.set(name, JSON.stringify(data), (err, reply) => {
        if (err) {
          reject(err);
        } else {
          resolve(reply);
        }
      });
    }
  })
}
const hmset = (name, data) => {
  return new Promise((resolve, reject) => {
    client.set(name, JSON.stringify(data), (err, reply) => {
      if (err) {
        reject(err);
      } else {
        resolve(reply);
      }
    });
  })
}
const hdel = (name, key) => {
  return new Promise((resolve, reject) => {
    if (key) {
      client.del(name, key, (err, reply) => {
        if(err) {
          reject(err);
        } else {
          resolve(reply)
        }
      });
    } else {
      client.del(name, key, (err, reply) => {
        if(err) {
          reject(err);
        } else {
          resolve(reply)
        }
      });
    }
  })
}

module.exports = {
  hget,
  hgetall,
  hset,
  hmset,
  hdel
}
